import React from 'react';
import './index.less';
import { Space, Button, Modal } from 'antd';
import { connect, history } from 'umi';
import CommonForm from '@/components/form';
import CommonContain from '@/components/contain';
import CommonTable from '@/components/table';
import CommonDialog from '@/components/dialog';
import Search from '@/components/search';
import { ExclamationCircleOutlined } from '@ant-design/icons';

@connect(({ article, loading }) => ({ article, loading }))
export default class MenuList extends React.Component {
  constructor(props) {
    super(props);
    this.formRef = React.createRef();
    this.state = {
      isLookInfo: false,
      dialogTitle: '新增菜单',
      optButtonType: null,
      infoContent: '',
    };
  }

  componentWillMount() {
    const that = this;
    const { id = null } = this.props.location.query || {};
    if (id) {
      // this.setState({
      //   isLookInfo: true
      // })
      this.props
        .dispatch({
          type: 'article/look',
          payload: { id },
        })
        .then(({ success, msg, data }) => {
          if (success) {
            const {
              articleHtml,
              articleSubTitle,
              articleDesc,
              articleTitle,
              id,
            } = data || {};
            that.setState(
              {
                // infoContent: articleHtml
              },
              () => {
                this.formRef.current.setFieldsValue({
                  articleSubTitle,
                  articleDesc,
                  articleTitle,
                  id,
                  articleHtml,
                });
              },
            );
          }
        });
    }
  }

  async componentDidMount() {
    // // 假设此处从服务端获取html格式的编辑器内容
    // const htmlContent =  fetchEditorContent()
    // // 使用BraftEditor.createEditorState将html字符串转换为编辑器需要的editorStat
    // this.setState({
    //     editorState: BraftEditor.createEditorState(htmlContent)
    // })
  }

  submitContent = async () => {
    // 在编辑器获得焦点时按下ctrl+s会执行此方法
    // 编辑器内容提交到服务端之前，可直接调用editorState.toHTML()来获取HTML格式的内容
    const htmlContent = this.state.editorState.toHTML();
    const result = await saveEditorContent(htmlContent);
  };

  handleEditorChange = (editorState) => {
    this.setState({ editorState });
  };

  /**
   * 数据单元格操作
   * @param {*} optType 操作方式 edit-编辑 info-详情 delete-删除
   * @param {*} text
   * @param {*} record 行记录
   * @param {*} index 下标
   */
  rowHandleEvent = (optType, text, record, index) => {
    const that = this;
    const emnuOptTypeObj = {
      edit: '编辑菜单',
      info: '查看详情',
      delete: '删除',
    };
    const { menuParentId, menuPath, menuName, id } = record || {};
    this.setState({
      dialogTitle: emnuOptTypeObj[optType],
      optButtonType: optType,
    });

    if (optType === 'edit' || optType === 'info') {
      this.refs['common-dialog'].setIsModalVisible(true);
      // FIX 防止dialog刚开始展示时对象组件还没完全创建 防止无法找到对象
      setTimeout(() => {
        this.formRef.current.setFieldsValue(
          { menuParentId, menuPath, menuName, id },
          100,
        );
      });
    }
    if (optType == 'delete') {
      Modal.confirm({
        title: '提示?',
        icon: <ExclamationCircleOutlined />,
        content: '确认删除当前选中记录？',
        okText: '确认',
        okType: 'danger',
        cancelText: '关闭',
        onOk() {
          that.props.dispatch({
            type: 'menu/del',
            payload: { id },
          });
        },
        onCancel() {},
      });
    }
    console.log('rowHandleEvent', optType, text, record, index);
  };

  /**
   * 返回
   */
  goBack = () => {
    history.go(-1);
  };

  /**
   * 保存
   */
  saveArticle = async () => {
    try {
      const values = await this.formRef.current.validateFields();
      const params = { ...values };
      params.articleHtml = values.articleHtml.toHTML();
      console.log(
        'Success:',
        params,
        values,
        values.articleHtml.isEmpty(),
        values.articleHtml.toText(),
        values.articleHtml.toHTML(),
        values.articleHtml.toRAW(),
      );
      this.props.dispatch({
        type: values.id ? 'article/update' : 'article/add',
        payload: params,
      });
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };

  /**
   * 新增｜详情｜修改表单元素
   */
  buildFormItem = () => {
    return [
      {
        formItem: {
          name: 'id',
          hidden: true,
        },
        formElement: {},
      },
      {
        formItem: {
          name: 'articleTitle',
          label: '文章标题',
          rules: [
            {
              required: true,
              message: '请输入文章标题',
            },
          ],
        },
        formElement: {
          'el-type': 'input',
          placeholder: '提示：请输入文章标题',
        },
      },
      {
        formItem: {
          name: 'articleSubTitle',
          label: '文章副标题',
          rules: [
            {
              required: false,
              message: '请输入文章副标题',
            },
          ],
        },
        formElement: {
          'el-type': 'input',
          placeholder: '提示：请输入菜单路径',
        },
      },
      {
        formItem: {
          name: 'articleDesc',
          label: '文章备注',
          rules: [
            {
              required: false,
              message: '请输入文章备注',
            },
          ],
        },
        formElement: {
          'el-type': 'input',
          placeholder: '提示：请输入文章备注',
        },
      },
      {
        formItem: {
          // name: 'articleContent',
          name: 'articleHtml',
          label: '文章内容',
          rules: [
            {
              required: true,
              message: '请输入文章内容',
            },
          ],
          labelCol: { span: 4 },
          wrapperCol: { span: 19 },
        },
        formElement: {
          'el-type': 'md',
          placeholder: '提示：请输入文章内容',
        },
      },
    ];
  };

  preview = () => {
    if (window.previewWindow) {
      window.previewWindow.close();
    }
    window.previewWindow = window.open();
    window.previewWindow.document.write(this.buildPreviewHtml());
    window.previewWindow.document.close();
  };
  buildPreviewHtml() {
    return `
      <!Doctype html>
      <html>
        <head>
          <title>Preview Content</title>
          <style>
            html,body{
              height: 100%;
              margin: 0;
              padding: 0;
              overflow: auto;
              background-color: #f1f2f3;
            }
            .container{
              box-sizing: border-box;
              width: 1000px;
              max-width: 100%;
              min-height: 100%;
              margin: 0 auto;
              padding: 30px 20px;
              overflow: hidden;
              background-color: #fff;
              border-right: solid 1px #eee;
              border-left: solid 1px #eee;
            }
            .container img,
            .container audio,
            .container video{
              max-width: 100%;
              height: auto;
            }
            .container p{
              white-space: pre-wrap;
              min-height: 1em;
            }
            .container pre{
              padding: 15px;
              background-color: #f1f1f1;
              border-radius: 5px;
            }
            .container blockquote{
              margin: 0;
              padding: 15px;
              background-color: #f1f1f1;
              border-left: 3px solid #d1d1d1;
            }
          </style>
        </head>
        <body>
          <div class="container">${this.state.editorState.toHTML()}</div>
        </body>
      </html>
    `;
  }

  render() {
    return (
      <CommonContain style={{ backgroundColor: '#fff', paddingTop: 20 }}>
        {/* 公共表单 */}
        <CommonForm
          ref={this.formRef}
          formFileds={this.buildFormItem()}
          otherProps={{
            style: { overflowY: 'auto', overflowX: 'hidden' },
            layout: 'horizontal',
            labelCol: { span: 4 },
            wrapperCol: { span: 12 },
          }}
        />
        <div style={{ textAlign: 'right', margin: '20px 20px 20px 0' }}>
          <Space wrap align={'center'} size={[8, 0]}>
            <Button onClick={this.goBack}>返 回</Button>
            <Button type="primary" onClick={this.saveArticle}>
              保 存
            </Button>
          </Space>
        </div>
      </CommonContain>
    );
  }
}
